package wsz.jpa;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author wsz
 * @date 2021/12/28 15:50
 **/
@Configuration
@EnableJpaRepositories(
        basePackages = "wsz",
        entityManagerFactoryRef = "exampleEntityManager",
        transactionManagerRef = "exampleTransactionManager"
)
@EnableTransactionManagement
public class JpaConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return new HikariDataSource();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean exampleEntityManager() {

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL57Dialect");

        vendorAdapter.setShowSql(true);
        vendorAdapter.setDatabase(Database.valueOf("MYSQL"));
        vendorAdapter.setGenerateDdl(false);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("wsz.pojo");
        factory.setDataSource(dataSource());
        factory.setJpaProperties(jpaProperties());

        return factory;

    }

    @Bean
    public Properties jpaProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.temp.use_jdbc_metadata_defaults", "false");
        properties.put("hibernate.ddl-auto", "update");
        return properties;
    }

    @Bean
    public PlatformTransactionManager exampleTransactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(exampleEntityManager().getObject());
        return txManager;

    }
}
